// import { getSceneByName } from '../three/ThreeScene.vue'
import * as Cesium from 'cesium'
import * as THREE from 'three'
import { waitUntilValueExist } from '../../utils/unsorted'

export class SyncThreeWithCesium {
    static instance = null
    static map = new Map()
    constructor({ cesiumCamera, threeCamera }) {
        this.cesiumCamera = cesiumCamera
        this.threeCamera = threeCamera
    }

    sync() {
        this.syncByCameraParameter()
        // this.syncByMatrix()
    }

    //
    syncByCameraParameter() {
        const { threeCamera: t, cesiumCamera: c } = this

        const inverseViewMatrixArray = Cesium.Matrix4.toArray(
            c.inverseViewMatrix
        )
        t.matrix.copy(new THREE.Matrix4().fromArray(inverseViewMatrixArray))

        t.matrix.decompose(t.position, t.quaternion, t.scale)

        const f = c.frustum
        // 不可能有人用带小数的degree吧
        const cFov = parseInt((180 / Math.PI) * f.fovy)
        if (
            t.near !== f.near ||
            t.far !== f.far ||
            t.aspect !== f.aspectRatio ||
            t.fov !== cFov
        ) {
            t.near = f.near
            t.far = f.far
            t.aspect = f.aspectRatio
            t.fov = cFov
            t.updateProjectionMatrix()
        }

        t.matrixAutoUpdate = true
    }

    // 此方法直接赋值矩阵，性能应该更好
    // 但控制权转给threejs后，改用matrixAutoUpdate = true之前 ,需要调用一次syncByCameraParameter
    syncByMatrix() {
        const { threeCamera, cesiumCamera } = this
        const projectionMatrixArray = Cesium.Matrix4.toArray(
            cesiumCamera.frustum.projectionMatrix
        )
        threeCamera.projectionMatrix.copy(
            new THREE.Matrix4().fromArray(projectionMatrixArray)
        )

        const inverseViewMatrixArray = Cesium.Matrix4.toArray(
            cesiumCamera.inverseViewMatrix
        )
        threeCamera.matrix.copy(
            new THREE.Matrix4().fromArray(inverseViewMatrixArray)
        )

        threeCamera.matrixAutoUpdate = false
        threeCamera.updateMatrixWorld(true)
    }
}
